package com.eagle.epay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eagle.epay.common.ResultVO;
import com.eagle.epay.constant.ResponseEnum;
import com.eagle.epay.entity.User;
import com.eagle.epay.exception.ServiceException;
import com.eagle.epay.mapper.UserMapper;
import com.eagle.epay.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author eagle
 * @since 2019-12-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

	@Override
//	taskExecutor在config包下有配置
	@Async("taskExecutor")
	public String doSomething() {
		try {
			Thread.sleep(3000);
			System.out.println("after 3s");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "Done";
	}

	@Override
	public void registerUser(User user) {
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.or(wa -> wa.eq("username",user.getUsername()))
				.or(wa -> wa.eq("email",user.getEmail()));
		List<User> list = this.list(wrapper);
		if(list.size()>0){
			for (User existUser : list) {
				if(StringUtils.isNotBlank(existUser.getUsername())){
					throw new ServiceException("The user is exist");
				}
				if(StringUtils.isNotBlank(existUser.getEmail())){
					throw new ServiceException("The user's mail is exist");
				}
			}
		}
		String dePasswod = DigestUtils.md5DigestAsHex(
				user.getPassword().getBytes(StandardCharsets.UTF_8));
		user.setPassword(dePasswod);
		boolean saveDone = this.save(user);
		if(! saveDone){
			throw new ServiceException("User register fail");
		}
	}

	@Override
	public User login(String userName, String password) {
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.eq("username",userName);
		User user = this.getOne(wrapper);
		if(null == user){
			throw new ServiceException(ResponseEnum.USER_OR_PASSWORD_ERROR.getDesc());
		}
		String userPsw = DigestUtils.md5DigestAsHex(
				password.getBytes(StandardCharsets.UTF_8));
		if(!StringUtils.equalsIgnoreCase(userPsw,user.getPassword())){
			throw new ServiceException(ResponseEnum.USER_OR_PASSWORD_ERROR.getDesc());
		}


		return user;
	}
}
